#!/usr/bin/python
import sys
import os

import cherrypy

import misc
import configuration
from uya.routerconf.configmod.configobj import configobj
import uya.routerconf as routerconf
from uya import view_callbacks

default_config_file = "/usr/share/uya/uya-web.conf"

def process_authfile(filename):
    return [map(str.strip, line.split(":", 1)) 
            for line in open(filename) 
            if ":" in line and not line.startswith("#")]

def changed_hash_callback():
    return routerconf.changed_hash()

def run_webserver(config, debug=False):    
    configuration_handler = configuration.Configuration(
        config["info"]["title"],
        config["config"]["configuration_file"],
        config["config"]["template_file"], 
        config["config"]["view_file"],
        config["info"]["html_templates_dir"],
        config["callbacks"],
        process_authfile(config["info"]["auth_file"]),
        changed_hash_callback,
        view_callbacks) 
    cherrypy.root = configuration_handler
    cherrypy.config.update(file=config["info"]["server_configuration"])
    if debug:
        cherrypy.config.update({"server.environment": 'development'})
        cherrypy.config.update({"server.socket_port": 8080})
        cherrypy.config.update({"server.socket_host": "0.0.0.0"})    
    def static_file(url, filename):
        cherrypy.config.configs[url] = {}
        section = cherrypy.config.configs[url]
        section["staticFilter.on"] = True
        section["staticFilter.dir"] = filename
    cherrypy.config.configs["/static"] = {}
    cherrypy.config.configs["/static"].update({
        'staticFilter.dir': config["info"]["static_dir"], 
        'staticFilter.on': True,
    })
    
    cherrypy.server.start()
   
def main(args):
    import optparse
    usage = """usage: %prog [OPTIONS]

    Simple configmod web frontend"""
    parser = optparse.OptionParser(usage)
    parser.add_option('-d', '--debug', dest='debug',
        action="store_true", default=False, help='Enable debug mode')
    parser.add_option('-f', '--config-file', dest='config_file',
        default=default_config_file, metavar="FILE", type="string", help='config file')
    options, args = parser.parse_args(args=args)
    if not os.path.isfile(options.config_file):
        misc.debug("configuration file not found: %s" % options.config_file)
        return 1
    config = configobj.ConfigObj(options.config_file)
    run_webserver(config, debug=options.debug)

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
